package com.mobile.collect.activitys;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.mobile.collect.R;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.beans.TypeInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.dialogs.PointDialog;
import com.mobile.collect.dialogs.SubmitTipDialog;
import com.mobile.collect.dialogs.v3.TipDialog;
import com.mobile.collect.present.BasePresent;
import com.mobile.collect.view.ImageLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.kit.NToast;
import cn.droidlover.xdroidmvp.mvp.XActivity;

public class DevicePointsActivity extends XActivity<BasePresent> implements ImageLayout.OnLayoutSuccessListener {
    @BindView(R.id.imageLayout)
    ImageLayout imageLayout;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_edit)
    ImageView btnEdit;
    @BindView(R.id.opIv)
    ImageView opIv;
    @BindView(R.id.btn_ok)
    ImageView btnOk;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    ArrayList<DevicePointInfo> list;

    Long picDbId;
    //    Long parentId;
    String picPath;
    boolean isShowError;

    DevicePicInfo picInfo;
    boolean isEditModel;
    @BindView(R.id.singelRb)
    RadioButton singelRb;
    @BindView(R.id.multipleRb)
    RadioButton multipleRb;
    @BindView(R.id.modelRg)
    RadioGroup modelRg;
//    @BindView(R.id.rightLayout)
//    LinearLayout rightLayout;
//    @BindView(R.id.bottomLayout)
//    LinearLayout bottomLayout;

    @Override
    public void initView() {
        super.initView();
        imageLayout.setOnLayoutSuccessListener(this);
        imageLayout.setListener(new ImageLayout.ImageLayoutListener() {
            @Override
            public void toUpdatePoint(DevicePointInfo pointInfo) {
                AddUnitPointActivity.lunch(DevicePointsActivity.this, true, picDbId, pointInfo.get_ID());
            }

            @Override
            public void toDelPoint(DevicePointInfo pointInfo) {
//                showDelTip(pointInfo);
            }

            @Override
            public void toSetBitMapInfo(int width, int height) {
                picInfo.setPicBitMapWidth(width);
                picInfo.setPicBitmapHeight(height);
                EntityManager.getInstance().saveDevicePicInfo(picInfo);
            }

            @Override
            public void showPointDialog(List<DevicePointInfo> list) {
                DevicePointsActivity.this.showPointDialog();
            }

            @Override
            public void loadPicSuccess() {
                loadPointList();
                if (isShowError) {
                    showToast("错误点已处理，可以继续导出了！");
                    setResult(Activity.RESULT_OK);
                    finish();
                }
            }
        });

        modelRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                chengeSelectModel();
//                switch (checkedId) {
//                    case R.id.singelRb:
//                        chengeSelectModel();
//                        break;
//                    case R.id.multipleRb:
//                        break;
//                }
            }
        });
    }


    @Override
    public void getDataFromServer() {

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_devicepoints;
    }

    @Override
    public void getIntentData() {
        picPath = getIntent().getStringExtra("picpath");
        isShowError = getIntent().getBooleanExtra("isShowError", false);
        picDbId = getIntent().getLongExtra("parentid", -1l);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        picInfo = EntityManager.getInstance().queryDevicePicIById(picDbId);

    }

    @Override
    public BasePresent newP() {
        return new BasePresent();
    }


    @OnClick({R.id.btn_back, R.id.btn_add, R.id.btn_copy, R.id.btn_edit, R.id.btn_ok, R.id.opIv
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                onBackPressed();
                break;
            case R.id.btn_add:
                if (Kits.Empty.check(list)) {
                    AddUnitPointActivity.lunch(this, false, picDbId, -1l);
                } else {
                    AddUnitPointActivity.lunch(this, false, picDbId, list.get(list.size() - 1).get_ID());
                }
                break;
            case R.id.btn_copy:
                CopyPicListActivity.lunch(this, picInfo.getParentId(), picDbId, false);
                break;

            case R.id.btn_edit:
                isEditModel = true;
                btnEdit.setVisibility(View.INVISIBLE);
                btnOk.setVisibility(View.VISIBLE);
                imageLayout.setCanEdit(true);
                modelRg.setVisibility(View.VISIBLE);
//                bottomLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_ok:
                isEditModel = false;
                btnEdit.setVisibility(View.VISIBLE);
                btnOk.setVisibility(View.INVISIBLE);
                imageLayout.setCanEdit(false);
                imageLayout.cancelSelected();
                modelRg.setVisibility(View.GONE);
                opIv.setVisibility(View.GONE);
                imageLayout.cancelSelected();
//                bottomLayout.setVisibility(View.INVISIBLE);
                break;
            case R.id.opIv:
                showPointDialog();
                break;
        }
    }

    public static void lunch(Context context, String picPath, Long parentId) {
        Intent intent = new Intent(context, DevicePointsActivity.class);
        intent.putExtra("picpath", picPath);
        intent.putExtra("parentid", parentId);
        context.startActivity(intent);
    }

    public static void lunch(Activity context, boolean isShowError, String picPath, Long parentId, int requestCode) {
        Intent intent = new Intent(context, DevicePointsActivity.class);
        intent.putExtra("picpath", picPath);
        intent.putExtra("parentid", parentId);
        intent.putExtra("isShowError", isShowError);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    public int getTitleLayoutResId() {
        return 0;
    }


    private void loadPointList() {
        list = new ArrayList<>();
        List dbList = EntityManager.getInstance().queryDevicePointInfoIByParentid(picDbId);
        list.addAll(dbList);
        if (list.size() != 0) {
            int expend = 0;
            for (DevicePointInfo pointInfo : list) {
                NLog.d("index", "expend=" + expend);
                String expendStr = getStartIndex(expend);
                pointInfo.setExpendNo(expendStr);
                String childTypeEn = pointInfo.getChildTypeEn();
                String typeEn = pointInfo.getTypeEn();

                int deviceCount = pointInfo.getDeviceCount();
                if (deviceCount == 0) {
                    deviceCount = 1;
                }
                if (TextUtils.isEmpty(typeEn) && !TextUtils.isEmpty(childTypeEn)) {
                    TypeInfo typeInfo = EntityManager.getInstance().queryTypeInfo(childTypeEn);
                    if (null != typeInfo) {
                        typeEn = typeInfo.getTypeCode();
                    }
                }

                if (TextUtils.equals(childTypeEn, "KP") && deviceCount > 1) {
                    String endStr = getStartIndex(expend + deviceCount - 1);
                    pointInfo.setLabelName("(" + expendStr + "-" + endStr + ")" + typeEn);
                } else {
                    pointInfo.setLabelName(expendStr + typeEn);
                }
                expend = expend + deviceCount;
            }

        }
        imageLayout.addPoints(list);
    }

    private String getStartIndex(int expend) {
        String expendStr;
        if (expend < 10) {
            expendStr = "00" + expend;
        } else if (expend >= 10 && expend < 100) {
            expendStr = "0" + expend;
        } else {
            expendStr = "" + expend;
        }
        return expendStr;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        chengeEditModel();
        loadPointList();
    }


    @Override
    public void onBackPressed() {
        checkPoints();
    }

    private void checkPoints() {
        List<DevicePointInfo> newList = new ArrayList<>();
        for (DevicePointInfo pointInfo : list) {
            if (pointInfo.getIsNewPoint()) {
                newList.add(pointInfo);
            }
        }
        if (newList.size() != 0) {
            showTip();
        } else {
            finish();
        }
    }


    private void saveNewPoints() {
        List<String> edpendNoList = new ArrayList<>();
        boolean hadRepeat = false;
        for (DevicePointInfo pointInfo : list) {
            String expendNo = pointInfo.getExpendNo();
            if (edpendNoList.contains(expendNo)) {
                TipDialog.show(this, pointInfo.getLabelName() + "扩展号重复，请更改！", TipDialog.TYPE.ERROR);
                hadRepeat = true;
                break;
            } else {
                edpendNoList.add(expendNo);
            }
        }
        if (!hadRepeat) {
            for (DevicePointInfo pointInfo : list) {
                pointInfo.setIsNewPoint(false);
            }
            EntityManager.getInstance().savePointInfo(list);
            finish();
        }
    }

    private void showDelTip() {
        final List<DevicePointInfo> selectPoints = imageLayout.getSelectPoints();
        if (Kits.Empty.check(selectPoints)) {
            TipDialog.show(this, "请点击选择删除点", TipDialog.TYPE.ERROR);
            return;
        }
        SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
            @Override
            public void submitClick() {
                list.removeAll(selectPoints);
                EntityManager.getInstance().delDevicePointInfo(selectPoints);
                imageLayout.delPoint(selectPoints);
                getP().sendPointChagneEvent(picInfo.getParentId(),picDbId);
                loadPointList();
            }

            @Override
            public void cancelClick() {

            }
        });
        submitTipDialog.display("温馨提示", "是否删除所选择 " + selectPoints.size() + "个点?", "取消", "删除");
    }


    private void showTip() {
        SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
            @Override
            public void submitClick() {
                saveNewPoints();
            }

            @Override
            public void cancelClick() {
//                List<DevicePointInfo> list = EntityManager.getInstance().queryDevicePointInfoIByParentid(picDbId, true);
                List<DevicePointInfo> delList = new ArrayList<>();
                for (DevicePointInfo pointInfo : list) {
                    if (pointInfo.getIsNewPoint()) {
                        delList.add(pointInfo);
                    }
                }
                list.removeAll(delList);
                imageLayout.removePoints(delList);
                EntityManager.getInstance().delDevicePointInfo(delList);
                getP().sendPointChagneEvent(picInfo.getParentId(),picInfo.get_ID());
                finish();
            }
        });
        submitTipDialog.display("温馨提示", "是否保存新增标签信息，新增标签在导出的时候不会显示在页面上!", "不保存", "保存");
    }

    @Override
    public boolean isNotWorkConnect() {
        return false;
    }

    @Override
    public void onLayoutSuccess() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        imageLayout.setImgBg(width, height, picPath);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        chengeEditModel();
        loadPointList();
    }

    private void chengeEditModel() {
        isEditModel = true;
        btnEdit.setVisibility(View.INVISIBLE);
        btnOk.setVisibility(View.VISIBLE);
        modelRg.setVisibility(View.VISIBLE);
//        bottomLayout.setVisibility(View.VISIBLE);
        imageLayout.setCanEdit(true);
    }

    private void chengeSelectModel() {
        if (singelRb.isChecked()) {
            imageLayout.setMultipleModel(false);
            opIv.setVisibility(View.INVISIBLE);
        } else {
            imageLayout.setMultipleModel(true);
            opIv.setVisibility(View.VISIBLE);
        }
    }

    PointDialog pointDialog;

    public void showPointDialog() {
        List<DevicePointInfo> list = imageLayout.getSelectPoints();
        if (list.size() == 0) {
            NToast.showToast(this, "您还没有选中点", 1);
            return;
        }
        boolean showUpdateBtn = list.size() == 1;
        pointDialog = new PointDialog(this, showUpdateBtn, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.delTv:
                        showDelTip();
                        break;
                    case R.id.x1Tv:
                        imageLayout.toSetLine("1x");
                        break;
                    case R.id.x2Tv:
                        imageLayout.toSetLine("2x");
                        break;
                    case R.id.x3Tv:
                        imageLayout.toSetLine("3x");
                        break;
                    case R.id.bg1Tv:
                        imageLayout.setBgType(0);
                        break;
                    case R.id.bg2Tv:
                        imageLayout.setBgType(1);
                        break;
                    case R.id.upTv:
                        imageLayout.toChangeDirection(270);
                        break;
                    case R.id.downTv:
                        imageLayout.toChangeDirection(90);
                        break;
                    case R.id.leftTv:
                        imageLayout.toChangeDirection(180);
                        break;
                    case R.id.rightTv:
                        imageLayout.toChangeDirection(0);
                        break;
                    case R.id.updateTv:
                        final List<DevicePointInfo> selectPoints = imageLayout.getSelectPoints();
                        if (selectPoints.size() == 1) {
                            AddUnitPointActivity.lunch(DevicePointsActivity.this, true, picDbId, selectPoints.get(0).get_ID());
                        }
                        break;
                }
                pointDialog.dismiss();
            }
        });
        pointDialog.display();
    }

    @Override
    protected void onDestroy() {
        imageLayout.saveAllPointWH();

        super.onDestroy();
    }
}